/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Service;


import CardGame.GameTable;
import Message.BeanConstant;
import Message.ServiceConstant;
import Constants.Command;
import Constants.PIConstants;
import Constants.Service;
import DataManager.DbManager;
import Shared.MapManager;
import DataManager.MySQLCommonDataProvider;
import DataManager.VCoreUserDataProvider;
import Utility.CommonUtils;
import PIServer.VMSProtocolHandler;
import Message.Message;
import java.util.Iterator;
import org.apache.mina.core.session.IoSession;
import Message.Base64;
import Message.SerializerHelper;
import java.util.ArrayList;

import java.io.InputStream;
import Utility.IOUtils;
import Utility.Memcache;

import PIServer.Main;
import Shared.GameMapObj;
import Shared.ItemObj;
import java.net.SocketAddress;
import java.util.Calendar;
import java.util.Date;
import org.apache.mina.core.future.CloseFuture;
import org.omg.CORBA.INVALID_ACTIVITY;
import vcore.obj.vcoreQUser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vcore.obj.VPayCard;
//import org.slf4j.profiler.Profiler;

/**
 *
 ** @author Nhan Nguyen
 */
@SuppressWarnings("deprecation")
public class ServerService {

    public static Logger log = LoggerFactory.getLogger(ServerService.class.getName());
    public static final int ID_ADMIN_ACCOUNT = 5125;
    public static boolean isEventStarted = false;

//    static Profiler profiler = null;
//
//    public static void initProfiler() {
//        profiler = new Profiler(ServerService.class.getName());
//        profiler.setLogger(log);
//    }
    public static void processCommand(IoSession session,
            int userID, String userName, Message clientMsg) {

//        if (profiler == null) {
//            initProfiler();
//        }

        int actionCommand = clientMsg.getActionCommand();
        switch (actionCommand) {
            case Command.SYS_LOGIN_REQUEST:
//                profiler.start("login");
                login(session, clientMsg);
//                profiler.stop().log();
                return;
            case Command.SYS_REGISTER_REQUEST:
                createAccount(session, clientMsg);
                break;

            case Command.CREATE_CHARACTER:
                createCharacter(session, userID, userName, clientMsg);
                break;

            case Command.SYS_UPDATE_ACCOUNT:
                updateAccountInfo(session, clientMsg);
                break;
            case Command.SYS_GET_ACCOUNT_INFO:
                getAccountInfo(session, userID);
                break;
            case Command.GET_AVATAR_IMAGE:
                getAvatar(session, userName, clientMsg);
                break;
            case Command.GET_SHOP_ITEMS:
                getShopItemList(session, userID, userName, clientMsg);
                break;
            case Command.GET_AVATAR_LIST_COUNT:
                getAvatarListCount(session);
                break;
            case Command.GET_AVATAR_ID:
                getAvatarId(session, userName, clientMsg);
                break;
            case Command.CHANGE_AVATAR:
                buyAvatar(session, userID, clientMsg);
//                changeAvatar(session, userID, clientMsg);
                break;
            case Command.GET_NICK_COLOR:
                getNickColor(session, userName, clientMsg);
                break;
            case Command.GET_USER_LEVEL:
                getUserLevel(session, userID, clientMsg);
                break;
            case Command.SYS_QUIT:
                //VMSProtocolHandler.sessionWrite(session, "QUIT");
                session.close(false);
                break;
//            case Command.GET_LIST_BEST_PLAYERS:
//                getBestPlayerList(session);
//                break;
//            case Command.GET_LIST_MOST_WEALTHY_PLAYERS:
//                getMostWealthyPlayerList(session);
//                break;
            case Command.BUY_ITEM:
                buyItem(session, userID, clientMsg);
                break;
            case Command.GET_ITEM_IMAGE:
                getItemImage(session, clientMsg);
                break;
            case Command.GET_USER_BALANCE:
                getUserBalance(session, userName, clientMsg);
                break;
//            case Command.ENTER_CHAT_ROOM:
//                sendChatterList(session, userName);
//                break;
//            case Command.SEND_CHAT_ROOM_TEXT:
//                sendChatRoomText(session, userName, clientMsg);
//                break;
//            case Command.LEAVE_CHAT_ROOM:
//                leaveChatRoom(session, userName);
//                break;
//            case Command.GET_USER_INVENTORY:
//                getUserInventory(session, userID, clientMsg);
//                break;
            case Command.GET_USER_DISPLAY_INFO:
                getUserDisplayInfo(session, userID, clientMsg);
                break;
            case Command.SET_USER_EMOTION_STATUS:
                setUserEmotionStatus(session, userName, clientMsg);
                break;
            case Command.SYS_CHECK_VERSION:
                checkVersion(session, userName, clientMsg);
                break;
            case Command.SYS_GET_SMS_SYNTAX:
                getSMSSyntax(session, userID, clientMsg);
                break;
            case Command.SYS_TOPUP_PHONE_CARD:
                insertPayCard(session, userName, userID, clientMsg);
                break;
            default:
                break;
        }
    }

    private static boolean createAccount(IoSession session, Message clientMsg) {

        UserObj userInfo = new UserObj();

        String userName = SerializerHelper.readString(clientMsg);
        userName = Base64.toString(userName);
        String password = SerializerHelper.readString(clientMsg);
        password = Base64.toString(password);
        String fullName = SerializerHelper.readString(clientMsg);
        String address = SerializerHelper.readString(clientMsg);
        int birthYear = SerializerHelper.readInt(clientMsg);
        int gender = SerializerHelper.readInt(clientMsg);
        String email = SerializerHelper.readString(clientMsg);

        boolean retVal = false;
        int userID = 0;

        VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
        MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
        try {

            if ((userName == null) || (userName.trim().length() == 0)) {
                // new user
                vcoreQUser new_user = dataManager.createGuestAccount();
                userName = new_user.username;
                password = new_user.password;
                userID = new_user.user_id;
                retVal = new_user.username != null;
            } else if (!dataManager.checkIfUserNameExists(userName)) {
                //Validate địa chỉ email
                //if (userInfo.validateEmail(email)) {
                retVal = dataManager.createAccount(userName, password, fullName, address, birthYear, gender, email);
                userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(userName);
                //}
            }

            Message msg;
            if (retVal) {
                msg = new Message(Command.REGISTER_SUCCESS, Service.CHAT_SERVICE);
                notifyNewUser(userID, userName, password);

                UserObj userExtraInfo = commonDataManager.getUserServiceInfoByUserID(userID);
                if (userExtraInfo == null) {
                    userInfo.userid = userID;
                    userInfo.username = userName;
                    userInfo.money = 0; // default money for new users
                    userInfo.avatar = 0;
                    userInfo.nickColor = 0xFFFFFF;
                    userInfo.emotion_status = null;
                    userInfo.user_level = 0;
                    userInfo.is_active = 'N';
                    commonDataManager.createNewUserRecord(userInfo);
                }

                userName = Base64.toBase64(userName);
                SerializerHelper.writeString(userName, msg);
                password = Base64.toBase64(password);
                SerializerHelper.writeString(password, msg);
            } else {
                msg = new Message(Command.REGISTER_FAIL, Service.CHAT_SERVICE);
            }
            session.write(msg);

        } catch (Exception ex) {
            log.error("createAccount", ex);
        } finally {
            dataManager.closeConnection();
            commonDataManager.closeConnection();
        }

        return retVal;
    }

    private static void createCharacter(IoSession session, int userID, String userName, Message clientMsg) {
        int gender = SerializerHelper.readInt(clientMsg);
        int hair = SerializerHelper.readInt(clientMsg);
        int head = SerializerHelper.readInt(clientMsg);
        int eyes = SerializerHelper.readInt(clientMsg);
        int shirt = SerializerHelper.readInt(clientMsg);
        int pant = SerializerHelper.readInt(clientMsg);
        MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
        byte result = commonDataManager.createCharacter(userID, gender, hair, head, eyes, shirt, pant);
        Message msg = new Message(Command.RESPONSE_CREATE_CHARACTER, Service.CHAT_SERVICE);
        SerializerHelper.writeInt(result, msg);
        session.write(msg);
    }

    /**
     * Cập nhật thông tin tài khoản
     * @author nguyendn
     * @param message
     */
    private static boolean updateAccountInfo(IoSession session, Message clientMsg) {

        String userName = SerializerHelper.readString(clientMsg);
        //userName = Base64.toString(userName);
        String fullName = SerializerHelper.readString(clientMsg);
        int gender = SerializerHelper.readInt(clientMsg);
        int birthYear = SerializerHelper.readInt(clientMsg);
        String address = SerializerHelper.readString(clientMsg);
        String cmnd = SerializerHelper.readString(clientMsg);
        String mobile = SerializerHelper.readString(clientMsg);
        int city = SerializerHelper.readInt(clientMsg);
        //String email = SerializerHelper.readString(clientMsg);
        boolean retVal = false;
        try {
            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
            retVal = dataManager.updateAccountInfo(userName, fullName, address, birthYear, gender, cmnd, mobile, city);
            //VMSProtocolHandler.sessionWrite(session, "ACCOUNT_UPDATED");

            Message msg;
            if (retVal) {
                msg = new Message(Command.RESPONSE_UPDATE_SUCCESS, Service.CHAT_SERVICE);
            } else {
                msg = new Message(Command.RESPONSE_UPDATE_FAIL, Service.CHAT_SERVICE);
            }
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("updateAccountInfoName", ex);
        }

        return retVal;
    }

    private static void getAccountInfo(IoSession session, int userID) {
        UserObj userInfo = new UserObj();
        //log.info("get account"+userName);
        try {
            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
            userInfo = dataManager.getAccountInfo(userID);
            MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
            CharacterObj charObj = commonDataManager.loadCharacterData(userID);
            ArrayList itemList = commonDataManager.getUserInventory(userID);
            Message msg = new Message(Command.RESPONSE_GET_ACCOUNT_INFO, Service.CHAT_SERVICE);
            SerializerHelper.writeInt(userInfo.user_level, msg);    // main level
            SerializerHelper.writeInt(1, msg);                      // farm level
            SerializerHelper.writeInt(userInfo.money, msg);         // main account
            SerializerHelper.writeInt(0, msg);                      // farm account
            SerializerHelper.writeByte(charObj.sex, msg);
            SerializerHelper.writeByte(charObj.hair, msg);
            SerializerHelper.writeByte(charObj.head, msg);
            SerializerHelper.writeByte(charObj.eyes, msg);
            SerializerHelper.writeByte(charObj.emotion, msg);
            SerializerHelper.writeByte(charObj.shirt, msg);
            SerializerHelper.writeByte(charObj.pant, msg);
            SerializerHelper.writeByte(charObj.headItem, msg);
            SerializerHelper.writeByte(charObj.handItem, msg);
            SerializerHelper.writeByte(charObj.faceItem, msg);
            SerializerHelper.writeByte(charObj.petType, msg);        // pet type
            SerializerHelper.writeByte(charObj.petHealth, msg);      // pet health
            SerializerHelper.writeByte(charObj.idxFriendly, msg);
            SerializerHelper.writeByte(charObj.idxHappy, msg);
            SerializerHelper.writeByte(charObj.idxHealthy, msg);
            SerializerHelper.writeByte(charObj.idxHostility, msg);
            SerializerHelper.writeByte(charObj.idxStylish, msg);
            SerializerHelper.writeInt(itemList.size(), msg);    // num of item
            for (int i=0; i<itemList.size(); i++) {
                ItemObj item = (ItemObj) itemList.get(i);
                SerializerHelper.writeInt(item.inventory_id, msg);
                SerializerHelper.writeInt(item.id, msg);
                SerializerHelper.writeString(item.name, msg);
                SerializerHelper.writeInt(item.category, msg);
                SerializerHelper.writeInt(item.level, msg);
                SerializerHelper.writeDateTime(item.creation_date, msg);
                SerializerHelper.writeDateTime(item.expired_date, msg);
                SerializerHelper.writeInt(item.usages, msg);
                SerializerHelper.writeInt(item.status, msg);
//              SerializerHelper.writeInt(getExtraRequirement(item.id), msg);
            }
            session.write(msg);

            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getAccountInfoID", ex);
        }
    }

    private static void getUserBalance(IoSession session, String userName, Message clientMsg) {
        try {
            String user = SerializerHelper.readString(clientMsg);
            if ((user == null) || (user.length() == 0)) {
                user = userName;
            }

            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            ;
            Message msg = new Message(Command.RESPONSE_GET_USER_BALANCE, Service.CHAT_SERVICE);
            SerializerHelper.writeInt(dataManager.retrieveAccountBalance(user), msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getUserBalance", ex);
        }
    }

    private static void getAvatarListCount(IoSession session) {
        try {
            Message msg = new Message(Command.RESPONSE_GET_AVATAR_LIST_COUNT, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int intAvatarCount = dataManager.getAvatarListCount();
            SerializerHelper.writeInt(intAvatarCount, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getAvatarListCount", ex);
        }
    }

//    private static void sendChatterList(IoSession session, String userName) {
//        log.info("sendChatterList");
//        //String room = session.getAttribute("room").toString();
//        session.setAttribute("chatRoom");
//        Message msg = new Message(Command.RESPONSE_ENTER_CHAT_ROOM, Service.CHAT_SERVICE);
//        int numOfChatter = 0;
//        try {
//            synchronized (VMSProtocolHandler.clientSessions.values()) {
//                Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//                while (iter.hasNext()) {
//                    IoSession s = (IoSession) iter.next();
//                    String user = s.getAttribute("user").toString();
//                    if (!user.equals(userName) && s.containsAttribute("chatRoom")) {
//                        log.info("user in room: " + user);
//                        Message msg1 = new Message(Command.RESPONSE_ENTER_CHAT_ROOM, Service.CHAT_SERVICE);
//                        SerializerHelper.writeBoolean(false, msg1);
//                        SerializerHelper.writeString(userName, msg1);
//                        s.write(msg1);
//                        numOfChatter++;
//                    }
//                }
//                SerializerHelper.writeBoolean(true, msg);
//                SerializerHelper.writeInt(numOfChatter, msg);
//            }
//            if (numOfChatter > 0) {
//                synchronized (VMSProtocolHandler.clientSessions.values()) {
//                    Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//                    while (iter.hasNext()) {
//                        IoSession s = (IoSession) iter.next();
//                        String user = s.getAttribute("user").toString();
//                        log.info("user in room: " + user);
//                        if (!user.equals(userName) && s.containsAttribute("chatRoom")) {
//                            SerializerHelper.writeString(user, msg);
//                        }
//                    }
//                }
//            }
//            session.write(msg);
//        } catch (Exception ex) {
//            log.error("sendChatterList", ex);
//        }
//    }
//
//    private static void sendChatRoomText(IoSession session, String userName, Message clientMsg) {
//        String text = SerializerHelper.readString(clientMsg);
////        String room = session.getAttribute("room").toString();
//        try {
//            synchronized (VMSProtocolHandler.clientSessions.values()) {
//                Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//                while (iter.hasNext()) {
//                    IoSession s = (IoSession) iter.next();
//                    String user = s.getAttribute("user").toString();
//                    if (!user.equals(userName) && s.containsAttribute("chatRoom")) {
//                        log.info("send chat to user: " + user);
//                        Message msg = new Message(Command.RESPONSE_RECEIVE_CHAT_ROOM_TEXT, Service.CHAT_SERVICE);
//                        SerializerHelper.writeString(userName, msg);
//                        SerializerHelper.writeString(text, msg);
//                        s.write(msg);
//                    }
//                }
//            }
//        } catch (Exception ex) {
//            log.error("sendChatRoomText", ex);
//        }
//    }
//
//    private static void leaveChatRoom(IoSession session, String userName) {
//        log.info("leave user: " + userName);
////        String chatRoom = session.getAttribute("chatRoom").toString();
//        session.removeAttribute("chatRoom");
//        try {
//            synchronized (VMSProtocolHandler.clientSessions.values()) {
//                Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//                while (iter.hasNext()) {
//                    IoSession s = (IoSession) iter.next();
//                    String user = s.getAttribute("user").toString();
//                    if (!user.equals(userName) && s.containsAttribute("chatRoom")) {
//                        log.info("leave alert to user: " + user);
//                        Message msg = new Message(Command.RESPONSE_LEAVE_CHAT_ROOM, Service.CHAT_SERVICE);
//                        SerializerHelper.writeString(userName, msg);
//                        s.write(msg);
//                    }
//                }
//            }
//        } catch (Exception ex) {
//            log.error("leaveChatRoom", ex);
//        }
//    }
    public static void SendSystemAnnoucement(IoSession session, String text, int duration) {
        if (session == null || (duration == 0 && session.getAttribute("table") != null)) // hanv add
        {
            return;
        }
        Message msg = new Message(Command.RESPONSE_SYSTEM_ANNOUCEMENT,
                Service.SYSTEM_SERVICE);
        SerializerHelper.writeString(text, msg);
        SerializerHelper.writeInt(duration, msg);
        session.write(msg);
    }

    private static void getUserLevel(IoSession session, int userID, Message clientMsg) {
        String ofUser = SerializerHelper.readString(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_USER_LEVEL, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int level = dataManager.getUserLevel(userID);
            SerializerHelper.writeInt(level, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getUserLevel", ex);
        }
    }

    private static void getUserDisplayInfo(IoSession session, int userID, Message clientMsg) {
        String ofUser = SerializerHelper.readString(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_USER_DISPLAY_INFO, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            UserObj user = dataManager.getUserServiceInfoByUserID(userID);
            String userName = (String) session.getAttribute("user");
            SerializerHelper.writeString(userName, msg);
            SerializerHelper.writeInt(user.avatar, msg);
            SerializerHelper.writeInt(user.nickColor, msg);
            SerializerHelper.writeString(user.emotion_status, msg);
            SerializerHelper.writeInt(user.user_level, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getUserDisplayInfo", ex);
        }
    }

    private static void notifyNewUser(int userID, String userName, String password) {
        MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
        try {
            String text = String.format(
                    StringConstant.strWelcomeNewUser,
                    userID, userName, password);
            int result = dataManager.createMessage(ID_ADMIN_ACCOUNT, userID, text, PIConstants.MESSAGE_TYPE_NORMAL);
            String suggestText = StringConstant.strSuggestFirstCash;
            result = dataManager.createMessage(ID_ADMIN_ACCOUNT, userID, suggestText, PIConstants.MESSAGE_TYPE_NORMAL);
        } catch (Exception ex) {
            log.error("notifyNewUser", ex);
        }
        dataManager.closeConnection();
    }

    private static void informNewClientVersion(IoSession session, String username) {
        Message msg = new Message(Command.RESPONSE_CHECK_VERSION, Service.CHAT_SERVICE);
        SerializerHelper.writeString(Main.client_version, msg);
        if (session == null) {
            return;
        }
        VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
        UserObj userInfo = dataManager.getAccountInfo(username);
        if (userInfo == null) {
            return;
        }
        log.info("User SMS PROVIDER :    " + userInfo.SMS_reg_provider);
        MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
        ArrayList smsSyntax = commonDataManager.getSMSSyntax(userInfo.userid, userInfo.SMS_reg_provider);
        String updateUrl = null;
        if (smsSyntax != null) {
            updateUrl = (String) smsSyntax.get(12);
        }
        if (updateUrl == null) {
            updateUrl = StringConstant.UpdateURL;
        }
        SerializerHelper.writeString(updateUrl, msg);
        log.info("Update Client Url :  " + updateUrl);
        session.write(msg);
        commonDataManager.closeConnection();
        dataManager.closeConnection();
    }

//    private void broadcast(String message)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if (s.isConnected())
//                {
//                    VMSProtocolHandler.sessionWrite(s, "SYSTEM_BROADCAST~" + message);
//                }
//            }
//        }
//    }
//    private void broadcastRoomList(String roomList)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if (s.isConnected())
//                {
//                    VMSProtocolHandler.sessionWrite(s, "ROOM_LIST~" + roomList);
//                }
//            }
//        }
//    }
//    private static void broadcastUserJoinedRoom(String userName, String room)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                    VMSProtocolHandler.sessionWrite(s, "BROADCAST_USER_JOINED_ROOM~" + userName);
//                }
//            }
//        }
//    }
//    private static void broadcastUserList(String room)
//    {
//        StringBuilder sb = new StringBuilder();
//
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                    sb.append(s.getAttribute("user").toString() + "~");
//                }
//            }
//
//            iter = VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                    VMSProtocolHandler.sessionWrite(s, "USER_LIST~" + sb.toString());
//                }
//            }
//        }
//    }
//    private void broadcastUserLeftRoom(String userName, String room)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter =VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                   VMSProtocolHandler.sessionWrite(s, "BROADCAST_USER_LEFT_ROOM~" + userName);
//                }
//            }
//        }
//    }
    public static void broadcastTable(String tableID, Message msg, int gameType) {
        broadcastTable(tableID, msg, null, gameType);
    }

    public static void broadcastTable(String tableID, Message msg, String exceptUserName, int gameType) {
//        synchronized (VMSProtocolHandler.clientSessions.values()) {
        //if (!RoomManager.tables.containsKey(tableID)) return;
        //GameTable gt = (GameTable)RoomManager.tables.get(tableID);

        //Anlh broadcast for BinhRoom
//        if (gameType == CardConstant.BINH_TYPE) {
//            GameCardTable gt;
//            if (!BinhRoomManager.getInstance().isTableExist(tableID)) {
//                return;
//            }
//            gt = (BinhTable) BinhRoomManager.getInstance().getTable(tableID);
//            for (int i = 0; i < gt.playerList.size(); i++) {
//                String userName = (String) gt.playerList.get(i);
//                if (userName.equals(exceptUserName)) {
//                    continue;
//                }
//                //IoSession userSession = VMSProtocolHandler.users.get(userID);
//                IoSession userSession = VMSProtocolHandler.getSessionByUserName(userName);
//                if ((userSession != null) && (userSession.isConnected())) {
//                    userSession.write(msg);
//                }
//            }
//        } else if (gameType == CardConstant.DOMINO_TYPE) {
//            if (!DominoRoomManager.getInstance().isTableExist(tableID)) {
//                return;
//            }
//            DominoTable gt = (DominoTable) DominoRoomManager.getInstance().getTable(tableID);
//
//            for (int i = 0; i < gt.playerList.size(); i++) {
//                String userName = (String) gt.playerList.get(i);
//                if (userName.equals(exceptUserName)) {
//                    continue;
//                }
//                //IoSession userSession = VMSProtocolHandler.users.get(userID);
//                IoSession userSession = VMSProtocolHandler.getSessionByUserName(userName);
//                if ((userSession != null) && (userSession.isConnected())) {
//                    userSession.write(msg);
//                }
//            }
//        } else
        if (gameType == CardConstant.TIENLEN_TYPE) {
            if (!CardGame.RoomManager.getInstance().isTableExist(tableID)) {
                return;
            }
            GameTable gt = (GameTable) CardGame.RoomManager.getInstance().getTable(tableID);
            for (int i = 0; i < gt.playerList.size(); i++) {
                String userName = (String) gt.playerList.get(i);
                if (userName.equals(exceptUserName)) {
                    continue;
                }
                //IoSession userSession = VMSProtocolHandler.users.get(userID);
                IoSession userSession = VMSProtocolHandler.getSessionByUserName(userName);
                if ((userSession != null) && (userSession.isConnected())) {
                    userSession.write(msg);
                }
            }
        }
//            else if (gameType == CardConstant.BATTLESHIP_TYPE) {
//            if (!BattleshipRoomManager.getInstance().isTableExist(tableID)) {
//                return;
//            }
//            BattleshipTable gt = (BattleshipTable) BattleshipRoomManager.getInstance().getTable(tableID);
//
//            for (int i = 0; i < gt.playerList.size(); i++) {
//                String userName = (String) gt.playerList.get(i);
//                if (userName.equals(exceptUserName)) {
//                    continue;
//                }
//
//                IoSession userSession = VMSProtocolHandler.getSessionByUserName(userName);
//                if ((userSession != null) && (userSession.isConnected())) {
//                    userSession.write(msg);
//                }
//            }
//        } else if (gameType == CardConstant.POKER_TYPE) {
//            if (!PokerRoomManager.getInstance().isTableExist(tableID)) {
//                return;
//            }
//            PokerTable gt = (PokerTable) PokerRoomManager.getInstance().getTable(tableID);
//
//            for (int i = 0; i < gt.playerList.size(); i++) {
//                String userName = (String) gt.playerList.get(i);
//                if (userName.equals(exceptUserName)) {
//                    continue;
//                }
//                //IoSession userSession = VMSProtocolHandler.users.get(userID);
//                IoSession userSession = VMSProtocolHandler.getSessionByUserName(userName);
//                if ((userSession != null) && (userSession.isConnected())) {
//                    userSession.write(msg);
//                }
//            }
//        }



//        }
    }

    public static void broadcastMap(int mapID, Message msg, String exceptUserName) {

        GameMapObj gt = (GameMapObj) MapManager.getInstance().getMap(mapID);
        if (gt == null) return;
        for (int i = 0; i < gt.getNumberOfUsers(); i++) {
            String userName = (String) gt.getUserAt(i);
            if (userName.equals(exceptUserName)) {
                continue;
            }
            //IoSession userSession = VMSProtocolHandler.users.get(userID);
            IoSession userSession = VMSProtocolHandler.getSessionByUserName(userName);
            if ((userSession != null) && (userSession.isConnected())) {
                userSession.write(msg);
            }
        }
    }

//    public static void broadcastRoom(String userName, String message, String room)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter =VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                   VMSProtocolHandler.sessionWrite(s, "BROADCAST_ROOM~" + userName + "~" + message);
//                }
//            }
//        }
//    }
//    private void broadcastGame(String userName, String message, String room)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter =VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                   VMSProtocolHandler.sessionWrite(s, "BROADCAST_GAME~" + userName + "~" + message);
//                }
//            }
//        }
//    }
//    private static void broadcastRoomMessage(String userName, String message, String room)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter =VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("room").toString().equalsIgnoreCase(room)))
//                {
//                   VMSProtocolHandler.sessionWrite(s, message + "~" + userName);
//                }
//            }
//        }
//    }
//    private void broadcastPrivate(String userNameFrom, String userNameTo, String message)
//    {
//        synchronized (VMSProtocolHandler.clientSessions.values())
//        {
//            Iterator<IoSession> iter =VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext())
//            {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("user").toString().equalsIgnoreCase(userNameTo)))
//                {
//                    VMSProtocolHandler.sessionWrite(s, "BROADCAST_PRIVATE_MESSAGE~" + userNameFrom + "~" + message);
//                    return;
//                }
//            }
//        }
//    }
//    public static void sendRoomList() {
//        StringBuilder sb = new StringBuilder();
//        String strRoom;
//        int roomCount = 0;
//        try
//        {
//            synchronized (rooms)
//            {
//                Iterator<String> iterRoom = rooms.iterator();
//                while (iterRoom.hasNext())
//                {
//                    strRoom = (String) iterRoom.next();
//                    synchronized (VMSProtocolHandler.clientSessions.values())
//                    {
//                        roomCount = 0;
//                        Iterator<IoSession> iterSessions =VMSProtocolHandler.clientSessions.values().iterator();
//
//                        while (iterSessions.hasNext())
//                        {
//                            IoSession s = (IoSession) iterSessions.next();
//                            if (s.isConnected())
//                            {
//                                if (s.getAttribute("room").toString().equalsIgnoreCase(strRoom))
//                                {
//                                    roomCount++;
//                                }
//                            }
//                        }
//                    }
//                    if (roomCount <= 0)
//                    {
//                        synchronized (rooms)
//                        {
//                            rooms.remove(strRoom);
//                        }
//                    }
//                    else
//                    {
//                        sb.append(strRoom + "|" + roomCount + "~");
//                    }
//                }
//            }
//        }
//        catch (Exception ex)
//        {
//        //log.error(ex.getMessage());
//        }
//
//        broadcastRoomList(sb.toString());
//    }
    public static void kick(String name) {
        synchronized (VMSProtocolHandler.clientSessions.values()) {
            Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
            while (iter.hasNext()) {
                IoSession session = (IoSession) iter.next();
                if (name.equals(session.getAttribute("user"))) {
                    log.info("(*) KICK user {}", name);
                    CloseFuture future = session.close(true);
                    // Wait until the connection is closed
                    future.awaitUninterruptibly();
//                    // Now connection should be closed.
                    if (!future.isClosed()) {
                        log.error("CANNOT KICK {}", name);
                        synchronized (VMSProtocolHandler.clientSessions.values()) {
                            VMSProtocolHandler.clientSessions.values().remove(session);
                        }
                    }
                    break;
                }
            }
        }
    }

    private static void eventAfterUserLogin(UserObj user) {
        try {
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();

            //@todo event: Từ ngày Open Beta những tất cả người chơi đăng nhập vào
            // hệ thống thứ 100, 200, 300 .... (chia hết 100) hàng ngày
            // sẽ nhận được phần thưởng 50.000$ từ hệ thống.
            boolean isReturn = checkSpecialReturnLogin(user);
            if (!isReturn) {
                checkSpecialLogin(user);
            }
            dataManager.notifyEventUserLogin(user);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("eventAfterUserLogin", ex);
        }
    }

//    private static void testDeadLock() {
//           // deadlock with three locks
//        Object lock1 = new String("lock1");
//        Object lock2 = new String("lock2");
//        Object lock3 = new String("lock3");
//
//        new DeadlockingThread("t1", lock1, lock2);
//        new DeadlockingThread("t2", lock2, lock3);
//        new DeadlockingThread("t3", lock3, lock1);
//
//        // deadlock with two locks
//        Object lock4 = new String("lock4");
//        Object lock5 = new String("lock5");
//
//        new DeadlockingThread("t4", lock4, lock5);
//        new DeadlockingThread("t5", lock5, lock4);
//    }
//
//    // There is absolutely nothing you can do when you have
//    // deadlocked threads.  You cannot stop them, you cannot
//    // interrupt them, you cannot tell them to stop trying to
//    // get a lock, and you also cannot tell them to let go of
//    // the locks that they own.
//    private static class DeadlockingThread extends Thread {
//
//        private final Object lock1;
//        private final Object lock2;
//
//        public DeadlockingThread(String name, Object lock1, Object lock2) {
//            super(name);
//            this.lock1 = lock1;
//            this.lock2 = lock2;
//            start();
//        }
//
//        public void run() {
//            while (true) {
//                f();
//            }
//        }
//
//        private void f() {
//            synchronized (lock1) {
//                g();
//            }
//        }
//
//        private void g() {
//            synchronized (lock2) {
//                // do some work...
//                for (int i = 0; i < 1000 * 1000; i++);
//            }
//        }
//    }
//    private static boolean checkIfRoomExists(String roomName)
//    {
//        return RoomManager.rooms.containsKey(roomName);
//        Iterator<String> iterRoom = rooms.iterator();
//        String strRoom = null;
//
//        while (iterRoom.hasNext())
//        {
//            strRoom = (String) iterRoom.next();
//            if (strRoom.equalsIgnoreCase(roomName))
//            {
//                return true;
//            }
//        }
//        return false;
//    }
//
//    private boolean createRoom(String roomName)
//    {
//        synchronized (rooms)
//        {
//            if (rooms.containsKey(roomName)) return false;
//            rooms.put(roomName, new ArrayList());
////            rooms.add(roomName);
//        }
//        ServerService.sendRoomList();
//        return true;
//    }
//    private void getAllDBUsernames(IoSession session)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            VMSProtocolHandler.sessionWrite(session, "INCOMING_DB_USERS_LIST~" + dataManager.getAllUsers());
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void getAllUserPropertyNames(IoSession session, String username)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            VMSProtocolHandler.sessionWrite(session, "INCOMING_USER_PROPERTY_NAMES~" + dataManager.getAllUserPropertyNames(username));
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void getAllGlobalPropertyNames(IoSession session)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            VMSProtocolHandler.sessionWrite(session, "INCOMING_GLOBAL_PROPERTY_NAMES~" + dataManager.getAllGlobalPropertyNames());
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private static void checkIfAccountIsDisabled(IoSession session, String username)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            VMSProtocolHandler.sessionWrite(session, "ACCOUNT_STATUS~" + dataManager.checkAccountStatus(username));
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void getLastLoginDate(IoSession session, String username)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            VMSProtocolHandler.sessionWrite(session, "INCOMING_LAST_LOGIN_DATE~" + dataManager.getLastLoginDate(username));
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void changePassword(IoSession session, String username, String oldPassword, String newPassword)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            if (dataManager.changePassword(username, oldPassword, newPassword))
//            {
//                //VMSProtocolHandler.sessionWrite(session, "PASSWORD_CHANGED");
//            }
//            else
//            {
//                //VMSProtocolHandler.sessionWrite(session, "PASSWORD_CHANGED_ERROR");
//            }
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void blockAddress(String ip)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            dataManager.blockAddress(ip);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void unblockAddress(String ip)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            dataManager.unblockAddress(ip);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
    private void deleteAccount(String userName) {
        try {
            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
            dataManager.deleteAccount(userName);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("deleteAccount", ex);
        }
    }

//    private void createAccount(IoSession session, String userName, String password)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//
//            if (dataManager.checkIfAccountExists(userName))
//            {
//                VMSProtocolHandler.sessionWrite(session, "ACCOUNT_CREATION_ERROR_USERNAME_EXISTS");
//            }
//            else
//            {
//                dataManager.createAccount(userName, password);
//                VMSProtocolHandler.sessionWrite(session, "ACCOUNT_CREATED");
//            }
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            VMSProtocolHandler.sessionWrite(session, "ACCOUNT_CREATION_ERROR_UNSPECIFIED");
//        }
//    }
//    private void disableAccount(String userName)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            dataManager.disableAccount(userName);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void enableAccount(String userName)
//    {
//        try
//        {
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            dataManager.enableAccount(userName);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//        }
//    }
//    private void loginNoPassword(IoSession session, String userName)
//    {
//        VCoreUserDataProvider dataManager = null;
//        String user = (String) session.getAttribute("user");
//
//        try
//        {
//
//            if (user != null)
//            {
//               VMSProtocolHandler.sessionWrite(session, "LOGIN_ERROR_USER_ALREADY_LOGGED_IN");
//                session.close(false);
//                return;
//            }
//
//            // check if the userName is already used
//            if (VMSProtocolHandler.users.containsKey(userName))
//            {
//               VMSProtocolHandler.sessionWrite(session, "LOGIN_ERROR_NAME_ALREADY_USED");
//                session.close(false);
//                return;
//            }
//
//            dataManager = DbManager.GetUserDataManager();
//
//            String str = session.getRemoteAddress().toString().replaceAll("/", "");
//            char c;
//            String ip = "";
//            StringBuilder sb = new StringBuilder();
//
//            for(int i = 0; i < str.length(); i++)
//            {
//                c = str.charAt(i);
//                if(c == ':')
//                {
//                    ip = sb.toString();
//                    break;
//                }
//                else
//                {
//                    sb.append(c);
//                }
//            }
//
//            if(ip.length() > 0)
//            {
//                if(dataManager.checkIfAddressIsBlocked(ip))
//                {
//                    session.close(false);
//                    return;
//                }
//            }
//
//            synchronized (VMSProtocolHandler.clientSessions.values())
//            {
//                VMSProtocolHandler.clientSessions.values().add(session);
//            }
//            session.setAttribute("user", userName);
//            session.setAttribute("room", "lobby");
//            session.setAttribute("ip", session.getRemoteAddress().toString());
//
//            synchronized (VMSProtocolHandler.users)
//            {
//                VMSProtocolHandler.users.put(user,session);
//            }
//
//           VMSProtocolHandler.sessionWrite(session, "LOGIN_OK");
//            broadcastUserJoinedRoom(userName, "lobby");
//        }
//        catch (Exception ex)
//        {
//        }
//        finally
//        {
//            dataManager.closeConnection();
//        }
//
//    }
    private static void login(IoSession session, Message msg) {

//        log.info("--------------------");
//
//        for (Object key : VMSProtocolHandler.rooms.keySet()) {
//            ArrayList arr = (ArrayList) VMSProtocolHandler.rooms.get(key);
//            log.info(key.toString());
//        }
//        log.info("--------------------");
//        for (Object key : VMSProtocolHandler.rooms.keySet()) {
//            ArrayList arr = (ArrayList) VMSProtocolHandler.rooms.get(key);
//            log.info(key.toString());
//        }
//        log.info("--------------------");

        String userName = SerializerHelper.readString(msg);
        userName = Base64.toString(userName);

        String password = SerializerHelper.readString(msg);
        password = Base64.toString(password);

        int status = SerializerHelper.readInt(msg);
        String customStatus = SerializerHelper.readString(msg);

        int BuildNo = SerializerHelper.readInt(msg);
        Message msgResponse = new Message(0, Service.SYSTEM_SERVICE);

        if (BuildNo < Main.CLIENT_BUILD_REQUIRED) {
            log.info("OLD VERSION {}", userName);
            msgResponse.setActionCommand(Command.LOGIN_FAIL);
            SerializerHelper.writeInt(Command.LOGIN_OLD_VERSION, msgResponse);
            session.write(msgResponse);

            // nform new release so client can download
            informNewClientVersion(session, userName);

            //session.close(false);
            return;
        }

        log.info("LOGIN " + userName);
        VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
        MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
//        vcoreQUser new_user = null;

        int loginResult;
//        boolean instantSignIn = false;
        try {
//            if (status >= 0) {
            // existing users

            if ((userName.trim().length() <= 0) || (password.trim().length() <= 0)) {
                log.info("LOGIN_ERROR_INVALID_PASSWORD_OR_USERNAME");
                //session.close(false);
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(Command.LOGIN_WRONG_USERNAME_OR_PASSWORD, msgResponse);
                session.write(msgResponse);
                session.close(false);
                return;
            }

//                profiler.startNested("CORE.login");
            loginResult = dataManager.isAuthenticated(userName, password);
//                profiler.startNested("other");

//            } else {
//                // new user
//                instantSignIn = true;
//                new_user = dataManager.createGuestAccount();
//                notifyNewUser(new_user.user_id, new_user.username, new_user.password);
//                userName = new_user.username;
//                isAuthorized = dataManager.isAuthenticated(new_user.username, new_user.password);
//            }

            if (loginResult == -2) {
                log.info("LOGIN_ERROR_USERNAME_NOT_EXIST");
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(5, msgResponse);
                session.write(msgResponse);
                session.close(false);
                return;
            }

            if (loginResult == -1) {
                log.info("LOGIN_ERROR_NOT_ACTIVATED");
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(Command.LOGIN_NOT_ACTIVATED, msgResponse);
                session.write(msgResponse);
                session.close(false);
                return;
            }

            if (loginResult == 0) {
                log.info("LOGIN_ERROR_WRONG_PASSWORD");
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(Command.LOGIN_WRONG_USERNAME_OR_PASSWORD, msgResponse);
                session.write(msgResponse);
                session.close(false);
                return;
            }

            if (loginResult == 1 && checkIfUserIsLoggedIn(userName)) {
                log.info("LOGIN_ERROR_USER_ALREADY_LOGGED_IN {}", userName);
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(Command.LOGIN_ALREADY_LOGGED, msgResponse);
                session.write(msgResponse);
                session.close(false);

                kick(userName);
//                    synchronized (VMSProtocolHandler.users) {
//                        VMSProtocolHandler.users.put(userName, null);
//                    }
                return;
            }

            UserObj user = dataManager.getAccountInfo(userName);
            if (user.isLocked()) {
                log.info("LOGIN_ERROR_NICK_LOCKED");
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(6, msgResponse);
                session.write(msgResponse);
                session.close(false);
                return;
            }

            if (user.isDisabled()) {
                log.info("LOGIN_ERROR_NICK_DISABLED");
                msgResponse.setActionCommand(Command.LOGIN_FAIL);
                SerializerHelper.writeInt(7, msgResponse);
                session.write(msgResponse);
                session.close(false);
                return;
            }

//            synchronized (VMSProtocolHandler.clientSessions.values()) {
                VMSProtocolHandler.clientSessions.put(user.userid, session);

                session.setAttribute("user", userName);
                session.setAttribute("room", "lobby");
//            session.setAttribute("ip", session.getRemoteAddress().toString());

                session.setAttribute("userid", user.userid);
                session.setAttribute("avatar", user.avatar);
                session.setAttribute("usertype", user.user_type);
                if (user.isVIPAccount()) {
                    session.setAttribute("vip", "yes");
                }
//            }


            String strUser = userName;
            if ((user.fullname != null) && (user.fullname.length() > 0)) {
                strUser = user.fullname;
            }
            if (!VMSProtocolHandler.leaveUserQueue.containsKey(userName)) {
                SendSystemAnnoucement(session, String.format(StringConstant.strWelcomeMessage, strUser), 15);
            }

//            synchronized (VMSProtocolHandler.users) {
//                VMSProtocolHandler.users.put(userName, session);
//            }
            log.info("LOGIN_OK");

            msgResponse.setActionCommand(Command.RESPONSE_LOGIN_SUCCESS);

            SerializerHelper.writeInt(user.userid, msgResponse);
            SerializerHelper.writeInt(user.avatar, msgResponse);
            SerializerHelper.writeInt(user.nickColor, msgResponse);
//            SerializerHelper.writeInt(user.user_level, msgResponse);
            SerializerHelper.writeBoolean(user.isVIPAccount(), msgResponse);  // is Vip account
            SerializerHelper.writeString(user.emotion_status, msgResponse);
//            SerializerHelper.writeInt(user.gender, msgResponse);
//            SerializerHelper.writeInt(user.hair, msgResponse);

//            int unreadMessage = commonDataManager.getUnreadMessage(user.userid);
//            SerializerHelper.writeInt(unreadMessage, msgResponse);

//            if (new_user != null) {
//                SerializerHelper.writeString(Base64.toBase64(new_user.username), msgResponse);
//                SerializerHelper.writeString(Base64.toBase64(new_user.password), msgResponse);
//            }
            SerializerHelper.writeInt(user.user_type, msgResponse);
            CharacterObj charObj = commonDataManager.loadCharacterData(user.userid);
            SerializerHelper.writeBoolean((charObj != null), msgResponse);  // is character created ?
            session.write(msgResponse);

            if (charObj != null) {
                msgResponse.setActionCommand(Command.RESPONSE_GET_CHARACTER_INFO);
                msgResponse.getBuffer().setPosition(0);
                SerializerHelper.writeInt(charObj.level, msgResponse);
                SerializerHelper.writeByte(charObj.sex, msgResponse);
                SerializerHelper.writeByte(charObj.hair, msgResponse);
                SerializerHelper.writeByte(charObj.head, msgResponse);
                SerializerHelper.writeByte(charObj.eyes, msgResponse);
                SerializerHelper.writeByte(charObj.emotion, msgResponse);
                SerializerHelper.writeByte(charObj.shirt, msgResponse);
                SerializerHelper.writeByte(charObj.pant, msgResponse);
                SerializerHelper.writeByte(charObj.headItem, msgResponse);
                SerializerHelper.writeByte(charObj.handItem, msgResponse);
                SerializerHelper.writeByte(charObj.faceItem, msgResponse);
                SerializerHelper.writeInt(charObj.petid, msgResponse);
                SerializerHelper.writeByte(charObj.idxFriendly, msgResponse);
                SerializerHelper.writeByte(charObj.idxHappy, msgResponse);
                SerializerHelper.writeByte(charObj.idxHealthy, msgResponse);
                SerializerHelper.writeByte(charObj.idxHostility, msgResponse);
                SerializerHelper.writeByte(charObj.idxStylish, msgResponse);
                session.write(msgResponse);
            }

            if (!VMSProtocolHandler.leaveUserQueue.containsKey(userName)) {
                eventAfterUserLogin(user);
            } else {
                recoverStatusForDisconnectUser(user, session);
            }

//            broadcastUserJoinedRoom(userName, "lobby");
        } catch (Exception ex) {
            log.error("login", ex);
        } finally {
            if (dataManager != null) {
                dataManager.closeConnection();
            }

            if (commonDataManager != null) {
                commonDataManager.closeConnection();
            }
        }
    }

    private static void recoverStatusForDisconnectUser(UserObj user, IoSession session) {

        LeaveUserObj leaveObj = VMSProtocolHandler.leaveUserQueue.remove(user.username);
        String tableID = leaveObj.leaveTable;
//        if (tableID.startsWith("TL")) {
//            GameTable gt = (GameTable) RoomManager.getInstance().getTable(tableID);
//            if (gt != null) {
//                log.info("rejoin user: {}", leaveObj.userName);
//                MySQLCommonDataProvider commonDataManager = commonDataManager = DbManager.GetCommonDataManager();
//                session.setAttribute("table", tableID);
//                int numOfLelfPlayer = gt.getNumberOfJoinedPlayers() - gt.playerThoatNgang.size();
//                Message msg = new Message(Command.BT_RESPOND_JOIN_TABLE_BEAN, Service.SYSTEM_SERVICE);
//                SerializerHelper.writeByte((byte) 1, msg);
//                SerializerHelper.writeString(tableID, msg);
//                SerializerHelper.writeLong(gt.betMoney, msg);
//                SerializerHelper.writeInt(numOfLelfPlayer, msg);
//                SerializerHelper.writeBoolean(gt.isPlaying, msg);
//                // hanv: khi reconnect thi chi tra ve nhung nguoi da joined vao ban & chua thoat ngang
//                int i = 0;
//                while (i < gt.getNumberOfJoinedPlayers()) {
//                    String player = (String) gt.getJoinedPlayerAt(i);
//                    if (gt.playerThoatNgang.indexOf(player) == -1) {    // chua thoat ngang
//                        SerializerHelper.writeString(player, msg);
//
//                        IoSession ses = VMSProtocolHandler.getSessionByUserName(player);
//                        if (ses == null) {
//                            // neu ko tim thay nguoi choi do mat ket noi --> kick
//                            if (!VMSProtocolHandler.leaveUserQueue.containsKey(player)) {
//                                gt.playerList.remove(i);
//                                continue;
//                            }
//                        }
//                        //                int playerID = (Integer) ses.getAttribute("userid");
//                        //                boolean isVIP = ses.getAttribute("vip") != null;
//
//                        UserObj userinfo = commonDataManager.getUserServiceInfoByUserName(player);
//                        SerializerHelper.writeLong(userinfo.money, msg);
//                        SerializerHelper.writeInt(userinfo.avatar, msg);
//                        SerializerHelper.writeInt(userinfo.nickColor, msg);
//                        SerializerHelper.writeInt(userinfo.user_level, msg);
//                        SerializerHelper.writeBoolean(userinfo.isVIPAccount(), msg);
//                        log.info(String.format("%s: Money (%d), Ava (%d), NickCo (%x), Lvl (%d), VIP (%d)",
//                                player, userinfo.money, userinfo.avatar,
//                                userinfo.nickColor, userinfo.user_level, userinfo.user_type));
//                    }
//                    i++;
//                }
//                SerializerHelper.writeInt(gt.tableType, msg);
//                session.write(msg);
//                commonDataManager.closeConnection();
//
//                if (gt.playerJoined.contains(user.username)) {
//                    if (gt.playerCongBai.contains(user.username)) {
//                        VMSProtocolHandler.serviceTienLen.broadcastSingleMessage(session, gt.tableID, "", StringConstant.strChatCommand + 0 + " " + user.username);
//                    } else {
//                        // hanv: update card if disconnected when playing
//                        msg = new Message(Command.UPDATE_CLIENT_CARDS, Service.GAME_CARD_SERVICE);
//                        SerializerHelper.writeString(tableID, msg);
//                        SerializerHelper.writeString(user.username, msg);
//                        SerializerHelper.writeBoolean(gt.isNewTurn, msg);
//
//                        int id = gt.playerJoined.indexOf(user.username);
//                        byte cardNo = gt.noCardsLeft[id];
//                        SerializerHelper.writeByte(cardNo, msg);
//
//                        for (i = 0; i < 13; i++) {
//                            if (gt.cards[id][i] != 0) {
//                                SerializerHelper.writeByte(gt.cards[id][i], msg);
//                            }
//                        }
//                        SerializerHelper.writeBoolean(gt.isFirstDeal, msg);
//                        int remainTime = 20 - (int) (System.currentTimeMillis() - gt.startTime) / 1000;
//                        log.debug("remainTime: " + remainTime);
//                        SerializerHelper.writeInt(remainTime, msg);
//                        SerializerHelper.writeString(gt.getJoinedPlayerAt(gt.nextTurnPlayer), msg);
//                        for (i = 0; i < gt.getNumberOfJoinedPlayers(); i++) {
//                            String player = (String) gt.getJoinedPlayerAt(i);
//                            if (gt.playerThoatNgang.indexOf(player) == -1) {
//                                SerializerHelper.writeBoolean(gt.playerBypassedTurn[i], msg);
//                            }
//                        }
//                        session.write(msg);
//
//                        if (gt.lastPlayedCards != null && gt.lastTurnPlayer != id) {
//                            msg = new Message(Command.BT_MOVE_BEAN, Service.GAME_CARD_SERVICE);
//                            SerializerHelper.writeInt(0, msg); // table type
//                            SerializerHelper.writeString(tableID, msg);
//                            SerializerHelper.writeString(gt.getJoinedPlayerAt(gt.lastTurnPlayer), msg);
//                            SerializerHelper.writeInt(gt.lastMoveType, msg);
//                            SerializerHelper.write(gt.lastPlayedCards, 0, gt.lastPlayedCards.length, msg);
//                            SerializerHelper.writeString(gt.getJoinedPlayerAt(gt.nextTurnPlayer), msg);
//                            SerializerHelper.writeBoolean(gt.isNewTurn, msg); // new turn
//                            session.write(msg);
//                        }
//                    }
//                }
//            }
//        }
//        if (tableID.startsWith("TB")) {
//            VMSProtocolHandler.serviceBinh.reconnect(session, leaveObj, user, tableID);
//        }
//        if (tableID.startsWith("DO")) {
//            VMSProtocolHandler.serviceDomino.reconnect(session, leaveObj, user, tableID);
//        }
//        if (tableID.startsWith("BS")) {
//            VMSProtocolHandler.serviceBattleship.reconnect(session, leaveObj, user, tableID);
//        }
//        if (tableID.startsWith("PK")) {
//            VMSProtocolHandler.servicePoker.reconnect(session, leaveObj, user, tableID);
//        }

    }

    private static boolean checkIfUserIsLoggedIn(String userName) {
        //String s;

//        synchronized (VMSProtocolHandler.users) {
//            return VMSProtocolHandler.users.containsKey(userName);
        Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
        while (iter.hasNext()) {
            IoSession ses = iter.next();
            String s = (String) ses.getAttribute("user");
            if ((s != null) && s.equals(userName)) {
                return true;
            }
        }
//        }
        return false;
    }
//
//    private void insertSessionProperty(IoSession session, String propertyName, String propertyValue) {
//        try {
//            session.setAttribute("CUSTOM_" + propertyName, propertyValue);
//        } catch (Exception ex) {
//            log.error("", ex);
//        }
//    }
//
//    private void readSessionProperty(IoSession session, String propertyName) {
//        try {
//            String s = (String) session.getAttribute("CUSTOM_" + propertyName);
//            VMSProtocolHandler.sessionWrite(session, "READ_SESSION_PROPERTY_RESULT~" + propertyName + "~" + s);
//        } catch (Exception ex) {
//            log.error("", ex);
//        }
//    }
//
//    private void updateSessionProperty(IoSession session, String propertyName, String propertyValue) {
//        try {
//            session.setAttribute("CUSTOM_" + propertyName, propertyValue);
//        } catch (Exception ex) {
//            log.error("", ex);
//        }
//    }

//    private void readProperty(IoSession session, String userName, String propertyName)
//    {
//        String propertyValue = "";
//
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            propertyValue = dataManager.readProperty(userName, propertyName);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//
//       VMSProtocolHandler.sessionWrite(session, "READ_PROPERTY_RESULT~" + propertyName + "~" + propertyValue);
//    }
//    private void updateProperty(String userName, String propertyName, String propertyValue)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            dataManager.updateProperty(userName, propertyName, propertyValue);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//
//    private void insertProperty(String userName, String propertyName, String propertyValue)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            dataManager.insertProperty(userName, propertyName, propertyValue);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//
//    private void deleteProperty(String userName, String propertyName)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            dataManager.deleteProperty(userName, propertyName);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//
//    private void readGlobalProperty(IoSession session, String propertyName)
//    {
//        String propertyValue = "";
//
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            propertyValue = dataManager.readGlobalProperty(propertyName);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//
//       VMSProtocolHandler.sessionWrite(session, "READ_GLOBAL_PROPERTY_RESULT~" + propertyName + "~" + propertyValue);
//    }
//
//    private void updateGlobalProperty(String propertyName, String propertyValue)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            dataManager.updateGlobalProperty(propertyName, propertyValue);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//
//    private void insertGlobalProperty(String propertyName, String propertyValue)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            dataManager.insertGlobalProperty(propertyName, propertyValue);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//
//    private void deleteGlobalProperty(String propertyName)
//    {
//        try
//        {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            dataManager.deleteGlobalProperty(propertyName);
//            dataManager.closeConnection();
//        }
//        catch (Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//    private void getUsersIP(IoSession session, String userName) {
//        try {
//            StringBuilder sb = new StringBuilder();
//            char c;
//            String str;
//
////            synchronized (VMSProtocolHandler.clientSessions.values()) {
//            Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
//            while (iter.hasNext()) {
//                IoSession s = (IoSession) iter.next();
//                if ((s.isConnected()) && (s.getAttribute("user").toString().equalsIgnoreCase(userName))) {
//                    str = s.getAttribute("ip").toString().replaceAll("/", "");
//
//                    for (int i = 0; i < str.length(); i++) {
//                        c = str.charAt(i);
//                        if (c == ':') {
//                            break;
//                        } else {
//                            sb.append(c);
//                        }
//                    }
//                    VMSProtocolHandler.sessionWrite(session, "INCOMING_USERS_IP~" + userName + "~" + sb.toString());
//                }
////                }
//            }
//        } catch (Exception ex) {
//            log.error("getUsersIP", ex);
//        }
//    }

    private static void getAvatarId(IoSession session, String username, Message clientMsg) {
        String ofuser = SerializerHelper.readString(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_AVATAR_ID, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(ofuser);
            int avatarId = dataManager.getUserAvatar(userID);
            SerializerHelper.writeString(username, msg);
            SerializerHelper.writeInt(avatarId, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getAvatarId", ex);
        }
    }

    private static void changeAvatar(IoSession session, int userID, Message clientMsg) {
        int newID = SerializerHelper.readInt(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_CHANGE_AVATAR, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();

            VCoreUserDataProvider userManager = DbManager.GetUserDataManager();
            UserObj userInfo = userManager.getAccountInfo(userID);

            boolean canChange = true;
            if (!userInfo.isVIPAccount() && dataManager.checkAvatarVIP(newID)) {
                canChange = false;
            }

            int avatarId = -1;
            if (canChange) {
                avatarId = dataManager.changeUserAvatar(userID, newID);
            }

            SerializerHelper.writeInt(avatarId, msg);
            session.write(msg);
            session.setAttribute("avatar", newID);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("changeAvatar", ex);
        }
    }

    private static void getNickColor(IoSession session, String userName, Message clientMsg) {
        String ofUser = SerializerHelper.readString(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_NICK_COLOR, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(ofUser);
            int avatarId = dataManager.getNickColor(userID);
            SerializerHelper.writeString(userName, msg);
            SerializerHelper.writeInt(avatarId, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getNickColor", ex);
        }
    }

    private static void getUserEmotionStatus(IoSession session, String userName, Message clientMsg) {
        String ofUser = SerializerHelper.readString(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_USER_EMOTION_STATUS, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(ofUser);
            String status = dataManager.getUserEmotionStatus(userID);
            SerializerHelper.writeString(status, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getUserEmotionStatus", ex);
        }
    }

    private static void setUserEmotionStatus(IoSession session, String userName, Message clientMsg) {
        String ofUser = SerializerHelper.readString(clientMsg);
        String status = SerializerHelper.readString(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_SET_USER_EMOTION_STATUS, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(ofUser);
            boolean result = dataManager.setUserEmotionStatus(userID, status);
            SerializerHelper.writeBoolean(result, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("setUserEmotionStatus", ex);
        }
    }

//    private static void addUserInventory(IoSession session, String username, Message clientMsg) {
//        int avatarId = SerializerHelper.readInt(clientMsg);
//        try {
//            Message msg = new Message(RESPONSE_SET_AVATAR_ID, Service.CHAT_SERVICE);
//            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
//            if (avatarId != 0) {
//                byte result = dataManager.addUserInventory(username, avatarId);
//                SerializerHelper.writeByte(result, msg);
//            }
//            session.write(msg);
//        } catch (Exception ex) {
//            log.error("", ex);
//        }
//    }
    private static void getAvatar(IoSession session, String username, Message clientMsg) {
        int avatarId = SerializerHelper.readInt(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_AVATAR_IMAGE, Service.CHAT_SERVICE);
            SerializerHelper.writeInt(avatarId, msg);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            if (avatarId != 0) {
//                String filePath = dataManager.getAvatarById(avatarId);
//                if(!filePath.equals("")){
//                    FileInputStream fis = new FileInputStream(filePath);
//                    byte[] buffer = new byte[fis.available()];
//                    fis.read(buffer);
//                    SerializerHelper.writeByte((byte)1,msg);
//                    SerializerHelper.write(buffer, 0, buffer.length, msg);
//                    fis.close();
//                }else{
                InputStream stream = dataManager.getItemImage(avatarId);
                if (stream == null) {
                    SerializerHelper.writeInt(0, msg);
                } else {
                    int bufsize = stream.available();
                    byte[] buffer = IOUtils.readFully(stream, bufsize, true);

                    SerializerHelper.writeInt(bufsize, msg);
                    SerializerHelper.write(buffer, 0, bufsize, msg);
                }
            }
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getAvatar", ex);
        }
    }

    private static void getItemImage(IoSession session, Message clientMsg) {
        int itemNum = SerializerHelper.readInt(clientMsg);
        try {
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            Message msg = new Message(Command.RESPONSE_GET_ITEM_IMAGE, Service.CHAT_SERVICE);
            SerializerHelper.writeInt(itemNum, msg);
            for (int i = 0; i < itemNum; i++) {
                int itemID = SerializerHelper.readInt(clientMsg);
                if (itemID != 0) {
                    InputStream stream = dataManager.getItemImage(itemID);
                    if (stream == null) {
                        SerializerHelper.writeInt(0, msg);
                    } else {
                        int bufsize = stream.available();
                        byte[] buffer = IOUtils.readFully(stream, bufsize, true);
                        SerializerHelper.writeInt(itemID, msg);
                        SerializerHelper.writeInt(bufsize, msg);
                        SerializerHelper.write(buffer, 0, bufsize, msg);
                    }
                }
            }
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("get item image list", ex);
        }
    }

    private static void getShopItemList(IoSession session, int userID, String userName, Message clientMsg) {
        int shopID = SerializerHelper.readInt(clientMsg);
        try {
            Message msg = new Message(Command.RESPONSE_GET_SHOP_ITEMS, Service.CHAT_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            ArrayList itemList = dataManager.getShopItemList(shopID);
            SerializerHelper.writeInt(shopID, msg);
            SerializerHelper.writeInt(itemList.size(), msg);
            for (int i = 0; i < itemList.size(); i++) {
                ItemObj item = (ItemObj) itemList.get(i);
                SerializerHelper.writeInt(item.id, msg);
                SerializerHelper.writeString(item.name, msg);
                SerializerHelper.writeInt(item.category, msg);
                SerializerHelper.writeInt(item.money, msg);
                SerializerHelper.writeInt(item.vipMoney, msg);
                SerializerHelper.writeInt(item.duration, msg);
                SerializerHelper.writeDateTime(item.expired_date, msg);
                SerializerHelper.writeString(item.description, msg);
                SerializerHelper.writeInt(item.usages, msg);
                SerializerHelper.writeInt(item.level, msg);
            }

            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("getAvatarList", ex);
        }
    }

//    private static void getUserInventory(IoSession session, int userID, Message clientMsg) {
//        try {
//            Message msg = new Message(Command.RESPONSE_GET_USER_INVENTORY, Service.CHAT_SERVICE);
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            ArrayList itemList;
//            itemList = dataManager.getUserInventory(userID);
//            SerializerHelper.writeInt(itemList.size(), msg);
//            for (int i = 0; i < itemList.size(); i++) {
//                ItemObj item = (ItemObj) itemList.get(i);
//                SerializerHelper.writeInt(item.id, msg);
//                SerializerHelper.writeInt(item.user_inventory_id, msg);
//                SerializerHelper.writeString(item.name, msg);
//                SerializerHelper.writeInt(item.category, msg);
//                SerializerHelper.writeDateTime(item.creation_date, msg);
//                SerializerHelper.writeDateTime(item.expired_date, msg);
//                SerializerHelper.writeInt(getExtraRequirement(item.id), msg);
//            }
//            dataManager.closeConnection();
//            session.write(msg);
//        } catch (Exception ex) {
//            log.error("getUserInventory", ex);
//        }
//    }

    // Check xem item nay co can thong tin phu nao khi su dung khong
//    private static int getExtraRequirement(int itemID) {
//        int extra = ItemService.NONE_EXTRA;
//
//        switch (itemID) {
//            case ItemService.LOA_LANG:
//                extra = ItemService.EXTRA_STRING;
//                break;
//        }
//
//        return extra;
//    }

//    private void addVivooCard(IoSession session, String username, Message clientMsg){
//        String serial =SerializerHelper.readString(clientMsg);
//        String pin    =SerializerHelper.readString(clientMsg);
//        try{
//            //Add card
//            //Cập nhật tài khoản
//            //Response
//            //Message msg = new Message(RESPONSE_GET_AVATAR_LIST,Service.CHAT_SERVICE);
//
//        }catch(Exception ex)
//        {
//            log.error("", ex);
//        }
//    }
//    private static void getMostWealthyPlayerList(IoSession session) {
//        try {
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            Message msg = new Message(Command.RESPONSE_LIST_MOST_WEALTHY_PLAYERS, Service.CHAT_SERVICE);
//            ArrayList<ArrayList> playerList = null;
//            Object obj = Memcache.getInstance().get("mostWealthyPlayerList");
//            if (obj != null) {
//                playerList = (ArrayList<ArrayList>) obj;
//            }
//            if (playerList == null) {
//                boolean updateResult = ResetTimeTask.updateBestPlayerList();
//                if (!updateResult) {
//                    return;
//                } else {
//                    playerList = (ArrayList<ArrayList>) Memcache.getInstance().get("mostWealthyPlayerList");
//                }
//            }
//
//            if (playerList != null) {
//                SerializerHelper.writeInt(playerList.size(), msg);
//                for (int i = 0; i < playerList.size(); i++) {
//                    ArrayList player = (ArrayList) playerList.get(i);
//                    int userID = (Integer) player.get(0);
//                    String userName = (String) player.get(1);
//                    SerializerHelper.writeString(userName, msg);
//                    SerializerHelper.writeInt((Integer) player.get(2), msg);
//
//                    //int userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(userName);
//                    UserObj user = dataManager.getUserServiceInfoByUserID(userID);
//                    SerializerHelper.writeInt(user.avatar, msg);
//                    SerializerHelper.writeInt(user.nickColor, msg);
//                    SerializerHelper.writeString(user.emotion_status, msg);
//                    SerializerHelper.writeInt(user.user_level, msg);
//                }
//                session.write(msg);
//                dataManager.closeConnection();
//            }
//        } catch (Exception ex) {
//            log.error("getMostWealthyPlayerList", ex);
//        }
//    }

//    private static void getBestPlayerList(IoSession session) {
//        try {
//            Message msg = new Message(Command.RESPONSE_LIST_BEST_PLAYERS, Service.CHAT_SERVICE);
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            ArrayList<ArrayList> playerList = null;
//            Object obj = Memcache.getInstance().get("bestPlayerList");
//            if (obj != null) {
//                playerList = (ArrayList<ArrayList>) obj;
//            }
//            if (playerList == null) {
//                boolean updateResult = ResetTimeTask.updateBestPlayerList();
//                if (!updateResult) {
//                    return;
//                } else {
//                    playerList = (ArrayList<ArrayList>) Memcache.getInstance().get("bestPlayerList");
//                }
//            }
//
//
//            SerializerHelper.writeInt(playerList.size(), msg);
//            for (int i = 0; i < playerList.size(); i++) {
//                ArrayList player = (ArrayList) playerList.get(i);
//                int userID = (Integer) player.get(0);
//                String userName = (String) player.get(1);
//                SerializerHelper.writeString(userName, msg);
//                SerializerHelper.writeInt(Integer.parseInt(player.get(2).toString()), msg);
//
//                //int userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(userName);
//                UserObj user = dataManager.getUserServiceInfoByUserID(userID);
//                SerializerHelper.writeInt(user.avatar, msg);
//                SerializerHelper.writeInt(user.nickColor, msg);
//                SerializerHelper.writeString(user.emotion_status, msg);
//                SerializerHelper.writeInt(user.user_level, msg);
//            }
//            session.write(msg);
//            dataManager.closeConnection();
//        } catch (Exception ex) {
//            log.error("getBestPlayerList", ex);
//        }
//    }

    private static void buyItem(IoSession session, int userID, Message clientMsg) {
        int itemID = SerializerHelper.readInt(clientMsg);
        int category = SerializerHelper.readInt(clientMsg);
        int result = 1;
        try {
            Message msg = new Message(Command.RESPONSE_BUY_ITEM, Service.SYSTEM_SERVICE);
            MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
            int userBalance = commonDataManager.retrieveAccountBalance(userID);
            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
            UserObj userInfo = dataManager.getAccountInfo(userID);

            int cost = commonDataManager.getItemCost(itemID, userInfo.isVIPAccount());

            if (userBalance >= cost) {
                if (category == PIConstants.ITEM_CATEGORY_FOOD) {
                    int healthIndex = commonDataManager.getItemHealthIndex(itemID);
                    ParadiseService.updateUserIndex(userID, PIConstants.USER_INDEX_HEALTHY, healthIndex);
                    // todo: add log item
                } else {
                    int unusedItemNo = commonDataManager.getUserUnusedItem(userID);
                    // su dung do ngay sau khi mua
                    if (category == PIConstants.ITEM_CATEGORY_ON_FACE
                            || category == PIConstants.ITEM_CATEGORY_IN_HAND
                            || category == PIConstants.ITEM_CATEGORY_ON_HEAD
                            || category == PIConstants.ITEM_CATEGORY_PANT
                            || category == PIConstants.ITEM_CATEGORY_SHIRT) {
                        // todo: check full inventory
                        ArrayList itemList = commonDataManager.getUserInventory(userID);
                        int i=0;
                        for (i=0; i<itemList.size(); i++) {
                            ItemObj item1 = (ItemObj) itemList.get(i);
                            if (item1.status == PIConstants.ITEM_STATUS_USING && item1.category == category) {
                                if (unusedItemNo < PIConstants.MAX_ITEM_UNUSED) {
                                    commonDataManager.updateUserInventoryStatus(item1.inventory_id,
                                        PIConstants.ITEM_STATUS_UNUSED);
                                    commonDataManager.addUserInventory(userID, itemID, PIConstants.ITEM_STATUS_USING);
                                    commonDataManager.setUserMoney(userID, userBalance - cost,
                                            String.format(StringConstant.strBuyItem, itemID), cost * -1, 
                                            CardConstant.PURCHASE_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                                    result = 1;
                                } else {
                                    result = 2;
                                }
                                break;
                            }
                        }

                        if (i == itemList.size()) { // ko co item cung loai dang dc su dung
                            if (unusedItemNo < PIConstants.MAX_ITEM_UNUSED) {
                                commonDataManager.addUserInventory(userID, itemID, PIConstants.ITEM_STATUS_USING);
                                commonDataManager.setUserMoney(userID, userBalance - cost,
                                        String.format(StringConstant.strBuyItem, itemID), cost * -1,
                                        CardConstant.PURCHASE_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                                result = 1;
                            } else {
                                result = 2;
                            }
                        }
                    } else {
                        if (unusedItemNo < PIConstants.MAX_ITEM_UNUSED) {
                            commonDataManager.addUserInventory(userID, itemID, PIConstants.ITEM_STATUS_UNUSED);
                            commonDataManager.setUserMoney(userID, userBalance - cost,
                                    String.format(StringConstant.strBuyItem, itemID), cost * -1, 
                                    CardConstant.PURCHASE_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                        } else {
                            result = 2;
                        }
                    }

                }
            } else {
                result = 0;
            }

            SerializerHelper.writeInt(result, msg);
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("buyItem", ex);
        }
    }

    private static void buyAvatar(IoSession session, int userID, Message clientMsg) {
        int avatarId = SerializerHelper.readInt(clientMsg);
        int currentAvatar = (Integer) session.getAttribute("avatar");
        try {
            Message msg = new Message(Command.RESPONSE_CHANGE_AVATAR, Service.CHAT_SERVICE);
            MySQLCommonDataProvider commonDataManager = DbManager.GetCommonDataManager();
            int userBalance = commonDataManager.retrieveAccountBalance(userID);
            VCoreUserDataProvider dataManager = DbManager.GetUserDataManager();
            UserObj userInfo = dataManager.getAccountInfo(userID);

            int cost = commonDataManager.getItemCost(avatarId, userInfo.isVIPAccount());

            if (userBalance >= cost && avatarId != currentAvatar) {
                avatarId = commonDataManager.changeUserAvatar(userID, avatarId);
                commonDataManager.setUserMoney(userID, userBalance - cost,
                        String.format(StringConstant.strBuyItem, avatarId), cost * -1, CardConstant.PURCHASE_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                SerializerHelper.writeInt(avatarId, msg);
                session.setAttribute("avatar", avatarId);
            } else {
                SerializerHelper.writeInt(-1, msg);
                if (userBalance < cost) {
                    SerializerHelper.writeString(StringConstant.strBuyAvatarNotEnoughMoneyError, msg);
                } else if (avatarId == currentAvatar) {
                    SerializerHelper.writeString(StringConstant.strBuySameAvatarError, msg);
                }
            }
            session.write(msg);
            dataManager.closeConnection();
        } catch (Exception ex) {
            log.error("buyAvatar", ex);
        }
    }

//    private static void getImage(IoSession session, String username, Message clientMsg) {
//        int imgID = SerializerHelper.readInt(clientMsg);
//        String imgName = SerializerHelper.readString(clientMsg);
//        // request type: 0: image only; 1: thumbnail only; 2: both
//        int requestType = SerializerHelper.readInt(clientMsg);
//        try {
//            Message msg = new Message(Command.RESPONSE_GET_IMAGE, Service.SYSTEM_SERVICE);
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            if ((imgID != 0) || (imgName != null)) {
//                ItemImageRequest itemImage = dataManager.getItemImage(imgID, imgName, (byte) requestType);
//                if (itemImage == null) {
//                    SerializerHelper.writeInt(0, msg);
//                } else {
//                    SerializerHelper.writeInt(itemImage.itemID, msg);
//                    SerializerHelper.writeString(itemImage.itemName, msg);
//                    SerializerHelper.writeInt(requestType, msg);
//
//                    if (requestType == 0 || requestType == 2) {
//                        int bufsize = itemImage.streamImage.available();
//                        byte[] buffer = IOUtils.readFully(itemImage.streamImage, bufsize, true);
//
//                        SerializerHelper.writeInt(bufsize, msg);
//                        SerializerHelper.write(buffer, 0, bufsize, msg);
//                    }
//
//                    if (requestType == 1 || requestType == 2) {
//                        int bufsize = itemImage.streamThumbImage.available();
//                        byte[] buffer = IOUtils.readFully(itemImage.streamThumbImage, bufsize, true);
//
//                        SerializerHelper.writeInt(bufsize, msg);
//                        SerializerHelper.write(buffer, 0, bufsize, msg);
//                    }
//                }
//            }
//            session.write(msg);
//            dataManager.closeConnection();
//        } catch (Exception ex) {
//            log.error("getImage", ex);
//        }
//    }

    private static void checkVersion(IoSession session, String username, Message clientMsg) {

        String version = SerializerHelper.readString(clientMsg);    // client version
        String platform = SerializerHelper.readString(clientMsg);
        int scrWidth = SerializerHelper.readInt(clientMsg);
        int scrHeight = SerializerHelper.readInt(clientMsg);
        String smsNumber = (clientMsg.isDataAvailable()) ? SerializerHelper.readString(clientMsg) : null;
        if (username == null) {
            // update from sign in form
            if (clientMsg.isDataAvailable()) {
                username = SerializerHelper.readString(clientMsg);
            } else {
                return;
            }
        }

        if (session == null) {
            return;
        }
        SocketAddress socketAddr = session.getRemoteAddress();

        String ipAddr = "(unknown)";
        if (socketAddr != null) {
            try {
                ipAddr = socketAddr.toString().replaceAll("/", "");
                int i = ipAddr.indexOf(':');
                if (i != -1) {
                    ipAddr = ipAddr.substring(0, i);
                }
            } catch (Exception ex) {
                log.error("checkVersion", ex);
            }
        }

        MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//        if (!session.containsAttribute("userid")) {
//            throw new IllegalArgumentException("Missing user ID!");
//        }

        int userID;
        if (session.containsAttribute("userid")) {
            // update after login
            userID = (Integer) session.getAttribute("userid");
        } else {
            // update from sign in form
            userID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(username);
        }
        if (platform.length() > 100) {
            platform = platform.substring(0, 99);   // hanv: fix bug too long platform
        }
        dataManager.updateClientUpdate(userID, username, platform, "J2ME",
                version, scrWidth, scrHeight, ipAddr);

//        if (version.compareTo(VMServer.client_version) < 0) {
        informNewClientVersion(session, username);
//        }
    }

    private static void getSMSSyntax(IoSession session, int userID, Message clientMsg) {

        String regNumber = SerializerHelper.readString(clientMsg);

        MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
        ArrayList smsSyntax = dataManager.getSMSSyntax(userID, regNumber);
        if (smsSyntax != null) {
            Message msg = new Message(Command.RESPONSE_GET_SMS_SYNTAX, Service.CHAT_SERVICE);
            String regNo = (String) smsSyntax.get(0);
            String regSyntax = (String) smsSyntax.get(1);
            String topupNo = (String) smsSyntax.get(2);
            String topupSyntax = (String) smsSyntax.get(3);
            String blockNo = (String) smsSyntax.get(4);
            String blockSyntax = (String) smsSyntax.get(5);
            String unblockNo = (String) smsSyntax.get(6);
            String unblockSyntax = (String) smsSyntax.get(7);
            String resetPassNo = (String) smsSyntax.get(8);
            String resetPassSyntax = (String) smsSyntax.get(9);
            String regVipNo = (String) smsSyntax.get(10);
            String regVipSyntax = (String) smsSyntax.get(11);
            if (regSyntax == null) {
                SerializerHelper.writeByte((byte)0, msg);       // SMS set is inactive
                session.write(msg);
            }
            else {
                SerializerHelper.writeByte((byte)1, msg);       // OK - thay doi sms number
                SerializerHelper.writeString(regNo, msg);
                SerializerHelper.writeString(regSyntax, msg);
                SerializerHelper.writeString(topupNo, msg);
                SerializerHelper.writeString(topupSyntax, msg);
                SerializerHelper.writeString(blockNo, msg);
                SerializerHelper.writeString(blockSyntax, msg);
                SerializerHelper.writeString(unblockNo, msg);
                SerializerHelper.writeString(unblockSyntax, msg);
                SerializerHelper.writeString(resetPassNo, msg);
                SerializerHelper.writeString(resetPassSyntax, msg);
                SerializerHelper.writeString(regVipNo, msg);
                SerializerHelper.writeString(regVipSyntax, msg);
                SerializerHelper.writeString("0984522102", msg);
                session.write(msg);
            }
        }
//        else {
//            Message msg = new Message(Command.RESPONSE_GET_SMS_SYNTAX, Service.CHAT_SERVICE);
//            SerializerHelper.writeByte((byte) 0, msg); // Failed - disable SMS
//            session.write(msg);
//        }
    }

//    private static boolean checkSMSSyntax(IoSession session, int userID, String smsNumber) {
//        MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//        ArrayList smsSyntax = dataManager.getSMSSyntax(userID, smsNumber);
//        String regNo = (smsSyntax == null) ? "8540" : (String) smsSyntax.get(0);
//
//        if (smsNumber.charAt(0) == regNo.charAt(0)                          // so sanh so dau va 2 so cuoi
//                && smsNumber.substring(2).equals(regNo.substring(2))) {
//            return true;
//        }
//
//        return false;
//    }
    private static void checkSpecialLogin(UserObj user) {
        try {
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            long numberLogin = 0;
            if (Memcache.getInstance().get("loginCount") == null) {
                Memcache.getInstance().set("loginCount", 3600 * 24, 1);
                log.info("Number login : " + Memcache.getInstance().get("loginCount").toString());
                return;
            } else {
                numberLogin = Long.parseLong(Memcache.getInstance().get("loginCount").toString());
                numberLogin++;
                log.info("Number login : " + numberLogin);
                Memcache.getInstance().set("loginCount", 3600 * 24, numberLogin);
//                log.info("Number login: " + Memcache.getInstance().get("loginCount").toString());
            }
            if (numberLogin % 500 == 0) {
//                notifyWinLoginGift(user, numberLogin);
                int userBalance = dataManager.retrieveAccountBalance(user.userid);
                userBalance += SPECIAL_LOGIN_GIFT_MONEY;
                dataManager.setUserMoney(user.userid, userBalance, String.format(StringConstant.strLoginGiftLog, numberLogin), SPECIAL_LOGIN_GIFT_MONEY, CardConstant.DAILY_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
            }

            //daily login gift (once a day)
            ArrayList<String> dailyLoginMoneyRec = (ArrayList<String>) Memcache.getInstance().get("LoginMoneyRec");

            if (dailyLoginMoneyRec == null) {
                dailyLoginMoneyRec = new ArrayList<String>();
            }

            if (!dailyLoginMoneyRec.contains(user.userid + "")) {
                dailyLoginMoneyRec.add(user.userid + "");
                addDailyLoginMoney(DAILY_LOGIN_GIFT_MONEY, user.userid);
                Memcache.getInstance().set("LoginMoneyRec", 3600 * 24, dailyLoginMoneyRec);
            }
        } catch (Exception ex) {
            log.error("checkSpecialLogin", ex);
        }
    }
    public static final int SPECIAL_LOGIN_GIFT_MONEY = 50000;
    public static final int DAILY_LOGIN_GIFT_MONEY = 5000;

//    private static void notifyWinLoginGift(UserObj user, long numberLogin) {
//        String text = String.format(StringConstant.strLoginGiftPrivateMessage /*, numberLogin*/);
//        ServerService.SendSystemAnnoucement(VMSProtocolHandler.getSessionByUserID(user.userid), text, 0);
//
//        text = String.format(StringConstant.strLoginGiftPublicMessage, user.username /*, numberLogin*/);
//        ItemFeatureService.addBroadcastMessage(text, ItemService.NORMAL_PRIORITY, ItemService.BROADCAST_ALL_SYSTEM);
//
////        int result = createMessage(ServerService.ID_ADMIN_ACCOUNT, userID, text);
////        UserService.notifyNewMessage(result,ServerService.ID_ADMIN_ACCOUNT,userID,text);
//
//    }

//    public void runUserPromotionProcedure(int admoney) {
//        try {
//            Statement s = conn.createStatement();
//            String sql = String.format("CALL user_promotion(%d);", admoney);
//            s.execute(sql);
//            s.close();
//        } catch (Exception e) {
//            log.info(e.getClass().getName(), e);
//        }
//    }
    private static void addDailyLoginMoney(int admoney, int userID) {
        try {
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            int userBalance = dataManager.retrieveAccountBalance(userID);
            userBalance += admoney;
            dataManager.setUserMoney(userID, userBalance, String.format(StringConstant.strDailyLoginGiftLog), admoney, CardConstant.DAILY_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);

            log.info("User login first time today");
            String text = String.format(StringConstant.strLoginOnceDayGiftPM, admoney);
            ServerService.SendSystemAnnoucement(VMSProtocolHandler.getSessionByUserID(userID), text, 0);

//            hanv rem
//            Statement s = conn.createStatement();
//            String sql = "DELETE FROM message WHERE text LIKE 'Hệ thống gửi tặng %' AND to_userid=" + userID + ";" ;
//            s.execute(sql);
//            s.close();

//            String text = String.format(StringConstant.strLoginOnceDayGiftPM, admoney);
//            int result = createMessage(ServerService.ID_ADMIN_ACCOUNT, userID, text);
//            log.info("User login first time today");
//            UserService.notifyNewMessage(result,ServerService.ID_ADMIN_ACCOUNT,userID,text);

        } catch (Exception ex) {
            log.error("addDailyLoginMoney", ex);
        }
    }
    private static final int MONEY_TRANSFER_LIMIT = 1000000; // 1mil.

    public static boolean transferMoney(int userID, String userName, String receiver, int money) {
        MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
        if ((money < 0) || (money > MONEY_TRANSFER_LIMIT)) {
            return false;
        }

        try {
            int userBalance = dataManager.retrieveAccountBalance(userID);
            int toUserID = VCoreUserDataProvider.getInstance().GetUserIdByUsername(receiver);
            int toUserBalance = dataManager.retrieveAccountBalance(toUserID);
            if ((money > userBalance) || (toUserID <= 0)) {
                return false;
            }

            dataManager.setUserMoney(userID, userBalance - money,
                    String.format(StringConstant.strTransferMoneyTo, money, receiver), money * -1, CardConstant.TRANFER_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
            dataManager.setUserMoney(toUserID, toUserBalance + money,
                    String.format(StringConstant.strTransferMoneyFrom, money, userName), money, CardConstant.TRANFER_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
            dataManager.createMessage(userID, toUserID,
                    String.format(StringConstant.strTransferMoneyMessage, money, userName), PIConstants.MESSAGE_TYPE_NORMAL);

        } catch (Exception ex) {
            log.error("transferMoney", ex);
        }
        return true;
    }

    public static void insertPayCard(IoSession session, String username, int userID, Message clientMsg) {
        try {
            if (session == null || username == null || userID == 0) {
                return;
            }
            String cardSeriesNumber = SerializerHelper.readString(clientMsg);
            String cardType = SerializerHelper.readString(clientMsg);
            if (cardSeriesNumber == null || cardType == null) {
                return;
            }
            VPayCard r = VCoreUserDataProvider.getInstance().CardChargingObj(username, cardSeriesNumber, cardType);
            Message respMsg = new Message(Command.RESPONSE_TOPUP_PHONE_CARD, Service.SYSTEM_SERVICE);
            SerializerHelper.writeInt(r.return_code, respMsg);
            SerializerHelper.writeString(r.return_msg, respMsg);
//            String strCardSuccess = String.format("User {0} nạp thẻ thành công, mệnh giá thẻ : {1}, quy ra xu : {2}, nhà cung cấp : {3}", username, r.return_cardmoney, r.return_gamemoney, cardType);
//            String strCardFailed = String.format("User {0} nạp thẻ thất bại, mệnh giá thẻ : {1}, số series : {2}, nhà cung cấp : {3}", username, r.return_cardmoney, cardSeriesNumber, cardType);
//            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
//            if (r.return_code <= 0) {
//                dataManager.logUserBalance(userID, CardConstant.CARD_SERVICE_ID, dataManager.retrieveAccountBalance(username), strCardFailed, 0, CardConstant.CARD_MONEY_TYPE);
//            } else {
//                dataManager.logUserBalance(userID, CardConstant.CARD_SERVICE_ID, dataManager.retrieveAccountBalance(username), strCardSuccess, r.return_gamemoney, CardConstant.CARD_MONEY_TYPE);
//            }
            session.write(respMsg);
        } catch (Exception ex) {
            log.error(ex.getClass().getName(), ex);
        }

    }

    public static void insertPayCardTest() {

        String cardSeriesNumber = "123456789";
        String cardType = "VNP";
        String username = "test2";
        VPayCard r = VCoreUserDataProvider.getInstance().CardChargingObj(username, cardSeriesNumber, cardType);
        System.out.println("card money : " + r.return_cardmoney);
        System.out.println("card gamemoney : " + r.return_gamemoney);
        System.out.println("return_code : " + r.return_code);
        System.out.println("return_msgs : " + r.return_msg);
    }

    public static String filterChatMessage(String inputString) {
        String result = inputString;
        for (int i = 0; i < StringConstant.badPhrases.length; i++) {
            if (inputString.indexOf(StringConstant.badPhrases[i]) >= 0) {
                result = result.replaceAll(StringConstant.badPhrases[i], "\u24D1");
            }
        }
        String[] words = result.split(" ");
        for (int i = 0; i < StringConstant.badWords.length; i++) {
            if (inputString.indexOf(StringConstant.badWords[i]) >= 0) {
                for (int j = 0; j < words.length; j++) {
                    if (words[j].equals(StringConstant.badWords[i])) {
                        words[j] = "\u24D1";
                    }
                }
            }
        }
        result = "";
        for(int i = 0; i < words.length-1;i++)
        {
            result += words[i] + " ";
        }
        return result + words[words.length-1];
    }
    public static Date EVENT_START = new Date();
    public static Date EVENT_END = new Date();
    public static int EVENT_LOW_STANDARD = 3;
    public static int EVENT_HIGH_STANDARD = 7;
    public static int EVENT_LOW_PRIZE = 10000;
    public static int EVENT_HIGH_PRIZE = 30000;
    public static int EVENT_TYPE = 1;
    private static final int EQUAL_TYPE = 1;
    private static final int EQUAL_OR_GREATER_TYPE = 0;

    private static boolean checkSpecialReturnLogin(UserObj user) {
        try {
            Date now = new Date();
            if (!now.after(EVENT_START) || !now.before(EVENT_END)) {
                return false;
            }

            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            Date lastlogin = dataManager.getLastLoginDate(user.userid);
            String strDate = String.format("%1$tY%1$tm%1$td", lastlogin);
            Date dt = new Date();
            int totalInactiveDay = Math.abs(daysBetween(dt, lastlogin));

            if (EVENT_TYPE == EQUAL_TYPE) {
                if (totalInactiveDay == EVENT_HIGH_STANDARD) {
                    String text = String.format(StringConstant.strReturnEventBigGiftMessage, user.username, EVENT_HIGH_PRIZE);
                    ServerService.SendSystemAnnoucement(VMSProtocolHandler.getSessionByUserID(user.userid), text, 0);

                    int userBalance = dataManager.retrieveAccountBalance(user.userid);
                    userBalance += EVENT_HIGH_PRIZE;
                    dataManager.setUserMoney(user.userid, userBalance, String.format(StringConstant.strReturnEventGiftLog, EVENT_HIGH_PRIZE, EVENT_HIGH_STANDARD), EVENT_HIGH_PRIZE, CardConstant.DAILY_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                    return true;
                }
                if (totalInactiveDay == EVENT_LOW_STANDARD) {
                    String text = String.format(StringConstant.strReturnEventSmallGiftMessage, user.username, EVENT_LOW_PRIZE);
                    ServerService.SendSystemAnnoucement(VMSProtocolHandler.getSessionByUserID(user.userid), text, 0);
                    int userBalance = dataManager.retrieveAccountBalance(user.userid);
                    userBalance += EVENT_LOW_PRIZE;
                    dataManager.setUserMoney(user.userid, userBalance, String.format(StringConstant.strReturnEventGiftLog, EVENT_LOW_PRIZE, EVENT_LOW_STANDARD), EVENT_LOW_PRIZE, CardConstant.DAILY_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                    return true;
                }
            } else if (EVENT_TYPE == EQUAL_OR_GREATER_TYPE) {
                if (totalInactiveDay >= EVENT_HIGH_STANDARD) {
                    String text = String.format(StringConstant.strReturnEventBigGiftMessage, user.username, EVENT_HIGH_PRIZE);
                    ServerService.SendSystemAnnoucement(VMSProtocolHandler.getSessionByUserID(user.userid), text, 0);

                    int userBalance = dataManager.retrieveAccountBalance(user.userid);
                    userBalance += EVENT_HIGH_PRIZE;
                    dataManager.setUserMoney(user.userid, userBalance, String.format(StringConstant.strReturnEventGiftLog, EVENT_HIGH_PRIZE, EVENT_HIGH_STANDARD), EVENT_HIGH_PRIZE, CardConstant.DAILY_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                    return true;
                }
                if (totalInactiveDay >= EVENT_LOW_STANDARD) {
                    String text = String.format(StringConstant.strReturnEventSmallGiftMessage, user.username, EVENT_LOW_PRIZE);
                    ServerService.SendSystemAnnoucement(VMSProtocolHandler.getSessionByUserID(user.userid), text, 0);
                    int userBalance = dataManager.retrieveAccountBalance(user.userid);
                    userBalance += EVENT_LOW_PRIZE;
                    dataManager.setUserMoney(user.userid, userBalance, String.format(StringConstant.strReturnEventGiftLog, EVENT_LOW_PRIZE, EVENT_LOW_STANDARD), EVENT_LOW_PRIZE, CardConstant.DAILY_MONEY_TYPE, CardConstant.ITEM_SERVICE_ID, -1);
                    return true;
                }
            }
        } catch (Exception ex) {
            log.error("check Special Return Login", ex);
        }
        return false;
    }

    public static int daysBetween(Date d1, Date d2) {
        return (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
    }
//    private static int getLastInactiveDate(int userID) {
//        int totatInactiveDay = 0;
//        try {
//            for (int i = 1; i <= 7; i++) {
//                Calendar today = Calendar.getInstance();
//                today.add(Calendar.DATE, -1 * i);
//                Date past = new Date(today.getTimeInMillis());
//                String strDate = String.format("%1$tY-%1$tm-%1$td", past);
//                int onlineTime = VCoreUserDataProvider.getInstance().GetActiontimeServiceByDay(userID, 1, strDate);
//                System.out.println("Date :   " + strDate + "           " + onlineTime);
//                if (onlineTime > 0) {
//                    return totatInactiveDay;
//                }
//                totatInactiveDay++;
//            }
//        } catch (Exception ex) {
//            log.error("get Inactice Date", ex);
//        }
//        return totatInactiveDay;
//    }
}
